package com.cpp.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cpp.common.enums.*;
import com.cpp.common.exception.BaseException;
import com.cpp.common.properties.PageProperties;
import com.cpp.common.result.PageResult;
import com.cpp.pojo.dto.resource.ResourcePageDTO;
import com.cpp.pojo.pojo.*;
import com.cpp.pojo.vo.question.QuestionVO;
import com.cpp.pojo.vo.resource.ResourceVO;
import com.cpp.pojo.vo.summary.ExamReport;
import com.cpp.server.aspect.annotation.UserRole;
import com.cpp.server.client.PptGenerationClient;
import com.cpp.server.context.UserHolder;
import com.cpp.server.mapper.*;
import com.cpp.server.service.AdminViewService;
import com.cpp.server.service.ExamService;
import com.cpp.server.service.ResourceService;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@RequiredArgsConstructor
@Slf4j
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    private final UserMapper userMapper;
    private final KnowledgeMapper knowledgeMapper;
    private final QuestionMapper questionMapper;
    private final PptGenerationClient pptGenerationClient;
    private final ChapterMapper chapterMapper;
    private final CourseMapper courseMapper;
    private final ExamMapper examMapper;
    private final PageProperties pageProperties;
    private final ResourceMapper resourceMapper;
    private final ExamService examService;
    private final AdminViewService adminViewService;
    private final AnswerRecordMapper answerRecordMapper;

    @SneakyThrows
    @Override
    @UserRole(roles = UserRoleEnum.TEACHER)
    public String generatePpt(Long chapterId) {
        User currentUser = UserHolder.getCurrentUser();
        //准备章节数据
        Chapter chapter = chapterMapper.selectById(chapterId);
        //准备知识点数据
        LambdaQueryWrapper<Knowledge> knowledgeQueryWrapper = new LambdaQueryWrapper<>();
        knowledgeQueryWrapper.eq(Knowledge::getChapterId, chapterId);
        List<Knowledge> knowledges = knowledgeMapper.selectList(knowledgeQueryWrapper);
        //拿到知识点里的所有题目id
        List<Long> knowledgeIds = new ArrayList<>();
        for (Knowledge knowledge : knowledges) {
            knowledgeIds.add(knowledge.getId());
        }
        log.info("知识点ids:{}", knowledgeIds);
        //准备题目数据
        List<Question> questions =new ArrayList<>();

        // ... existing code ...
        if (knowledgeIds == null || knowledgeIds.isEmpty()) {
            questions = Collections.emptyList();
        } else {
            LambdaQueryWrapper<Question> questionQueryWrapper = new LambdaQueryWrapper<>();
            questionQueryWrapper.in(Question::getKnowledgeIds, knowledgeIds);
            questions = questionMapper.selectList(questionQueryWrapper);
        }
// ... existing code ...

        //生成ppt
        String content = "生成四个ppt部分，part1，目录，part2章节介绍" + chapter.toString() + "part3课程知识点内容讲解" + knowledges.toString() + "part4课后练习" + questions.toString();
        Map<String, Object> options = new HashMap<>();
        // 调用api用大纲生成ppt
        String pptUrl = pptGenerationClient.generatePptByQuery(content, "testppt.ppt", options);
        //业务数据准备
        Resource resource = Resource
                .builder()
                .filePath(pptUrl)
                .userId(currentUser.getId())
                .courseId(chapter.getCourseId())
                .type(ResourceType.COURSE_WARE.getType())//ppt
                .build();
        //操作数据库
        save(resource);

        return pptUrl;
    }

    @SneakyThrows
    @Override
    @UserRole(roles = UserRoleEnum.TEACHER)
    public String generateExamReviewPpt(Long examId) {
        User currentUser = UserHolder.getCurrentUser();
        //查询考试
        Exam exam = examMapper.selectById(examId);
        //判断考试状态
        if (exam.getEndTime().isAfter(LocalDateTime.now())) {
            throw new BaseException("考试未结束,无法总结");
        }
        if (exam.getStatus() == ExamStatus.UNPUBLISHED.getCode()) {
            throw new BaseException("考试未发布,无法总结");
        }
        //准备数据
        //考试报告
        ExamReport examReport = examService.analysisReport(examId);
        //考试错题
        LambdaQueryWrapper<AnswerRecord> answerRecordQueryWrapper = new LambdaQueryWrapper<>();
        answerRecordQueryWrapper.eq(AnswerRecord::getExamId, examId);
        List<AnswerRecord> answerRecords = answerRecordMapper.selectList(answerRecordQueryWrapper);

        String content = "考试总体报告" + examReport + "学生错题记录" + answerRecords;
        //生成ppt
        Map<String, Object> options = new HashMap<>();
        // 调用api用大纲生成ppt
        String pptUrl = pptGenerationClient.generatePptByQuery(content, "testppt.ppt", options);
        //业务数据准备
        Resource resource = Resource
                .builder()
                .filePath(pptUrl)
                .userId(currentUser.getId())
                .courseId(exam.getCourseId())
                .type(ResourceType.EXAM_REVIEW.getType())//ppt
                .build();
        //操作数据库
        save(resource);
        return pptUrl;
    }

    @Override
    @UserRole(roles = UserRoleEnum.ADMIN)
    public PageResult listResourceBySubject(ResourcePageDTO resourcePageDTO) {

        Integer page = resourcePageDTO.getPageNum();
        Integer pageSize = resourcePageDTO.getPageSize();

        if (page == null || page <= 0) {
            page = pageProperties.getPage();
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = pageProperties.getPageSize();
        }
        Long subjectId = resourcePageDTO.getSubjectId();

        //查询课程
        LambdaQueryWrapper<Course> courseWrapper = new LambdaQueryWrapper<>();
        courseWrapper.eq(subjectId != null, Course::getSubjectId, subjectId);
        List<Course> courses = courseMapper.selectList(courseWrapper);
        List<Long> courseIds = courses.stream().map(Course::getId).toList();

        //mp分页查询
        LambdaQueryWrapper<Resource> resourceWrapper = new LambdaQueryWrapper<>();
        resourceWrapper.in(!courseIds.isEmpty(), Resource::getCourseId, courseIds);
        //加上多表查询
        Page<Resource> pageQuery = new Page<>(page, pageSize);
        Page<Resource> pageResource = page(pageQuery, resourceWrapper);

        List<ResourceVO> resourceVOList = new ArrayList<>();

        List<Resource> records = pageResource.getRecords();
        for (Resource record : records) {
            User user = userMapper.selectById(record.getUserId());
            Course course = courseMapper.selectById(record.getCourseId());
            String resourceType = ResourceType.getType(record.getType()).getDescription();
            resourceVOList.add(ResourceVO.builder()
                    .realName(user.getRealName())
                    .resourceType(resourceType)
                    .courseName(course.getName())
                    .filePath(record.getFilePath())
                    .build());
        }


        return new PageResult(pageResource.getTotal(), resourceVOList);
    }


    @Override
    @UserRole(roles = UserRoleEnum.ADMIN)
    public PageResult listQuestion(ResourcePageDTO resourcePageDTO) {
        Integer page = resourcePageDTO.getPageNum();
        Integer pageSize = resourcePageDTO.getPageSize();

        if (page == null || page <= 0) {
            page = pageProperties.getPage();
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = pageProperties.getPageSize();
        }
        Long subjectId = resourcePageDTO.getSubjectId();
        //查询课程
        LambdaQueryWrapper<Course> courseWrapper = new LambdaQueryWrapper<>();
        courseWrapper.eq(subjectId != null, Course::getSubjectId, subjectId);
        List<Course> courses = courseMapper.selectList(courseWrapper);
        List<Long> courseIds = courses.stream().map(Course::getId).toList();

        //分页查询
        LambdaQueryWrapper<Question> questionWrapper = new LambdaQueryWrapper<>();
        questionWrapper.in(!courseIds.isEmpty(), Question::getCourseId, courseIds);
        Page<Question> pageQuery = new Page<>(page, pageSize);
        Page<Question> pageQuestion = questionMapper.selectPage(pageQuery, questionWrapper);

        //数据封装
        List<Question> questions = pageQuestion.getRecords();
        List<QuestionVO> questionVOS = new ArrayList<>();
        for (Question question : questions) {
            Exam exam = examMapper.selectById(question.getExamId());

            if (exam == null){
                continue;
            }
            questionVOS.add(QuestionVO.builder()
                    .examTitle(exam.getExamTitle())
                    .courseName(courseMapper.selectById(question.getCourseId()).getName())
                    .type(question.getType())
                    .difficulty(question.getDifficulty())
                    .difficultyName(QuestionDifficultyType.getMessageByCode(question.getDifficulty()))
                    .score(question.getScore())
                    .content(question.getContent())
                    .answer(question.getAnswer())
                    .analysis(question.getAnalysis())
                    .build());
        }

        return new PageResult(pageQuestion.getTotal(), questionVOS);
    }


}
